import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Optional;

@WebServlet("/diary")
public class DiaryServlet extends HttpServlet {
    private final UserRepository service = new UserRepository();

    // 处理GET请求（跳转编辑页）
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");

        // 未登录时重定向到登录页
        if (user == null) {
            resp.sendRedirect(req.getContextPath() + "/login.jsp"); // 关键修改点1：添加.jsp后缀
            return;
        }

        String action = req.getParameter("action");
        if ("create".equals(action)) {
            // 清空编辑页面的旧数据
            req.removeAttribute("diary");
            req.getRequestDispatcher("/edit.jsp").forward(req, resp);
        } else if ("edit".equals(action)) {
            String diaryId = req.getParameter("id");
            Optional<Diary> diary = user.getDiaryById(diaryId);

            // 找到日记时跳转编辑页
            if (diary.isPresent()) {
                req.setAttribute("diary", diary.get());
                req.getRequestDispatcher("/edit.jsp").forward(req, resp);
            }
            // 未找到日记时重定向到主页
            else {
                resp.sendRedirect(req.getContextPath() + "/home.jsp"); // 关键修改点2：路径修正
            }
        }
    }

    // 处理POST请求（数据操作）
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");

        // 未登录时重定向到登录页
        if (user == null) {
            resp.sendRedirect(req.getContextPath() + "/login.jsp"); // 关键修改点3：添加.jsp后缀
            return;
        }

        try {
            String action = req.getParameter("action");
            switch (action) {
                case "create":
                    handleCreate(req, user);
                    break;
                case "update":
                    handleUpdate(req, user);
                    break;
                case "delete":
                    handleDelete(req, user);
                    break;
            }
            // 操作完成后统一跳转主页
            resp.sendRedirect(req.getContextPath() + "/home.jsp"); // 关键修改点4：路径修正
        } catch (Exception e) {
            // 错误处理时保留在主页
            req.setAttribute("error", "操作失败: " + e.getMessage());
            req.getRequestDispatcher("/home.jsp").forward(req, resp);
        }
    }

    // 新增日记逻辑
    private void handleCreate(HttpServletRequest req, User user) {
        service.saveDiary(
                user.getUsername(),
                new Diary(
                        req.getParameter("title"),
                        req.getParameter("content")
                )
        );
    }

    // 更新日记逻辑
    private void handleUpdate(HttpServletRequest req, User user) {
        String diaryId = req.getParameter("id");
        user.getDiaryById(diaryId).ifPresent(d -> {
            d.setTitle(req.getParameter("title"));
            d.setContent(req.getParameter("content"));
        });
    }

    // 删除日记逻辑
    private void handleDelete(HttpServletRequest req, User user) {
        service.deleteDiary(user.getUsername(), req.getParameter("id"));
    }
}